import {useLocation} from "@@/exports";
import {useMemo, useState} from "react";
import queryString, {ParsedQuery} from "query-string";
import {BizSearchType, searchTypeMap} from "@/pages/HomePage/BizSearchBar";


export const getLastQueryValue = (query: ParsedQuery, key: string): string | undefined => {
  const value = query[key];
  if (Array.isArray(value)) {
    // 多值情况，返回最后一个元素
    return value[value.length - 1] || undefined;
  }
  // 单值情况，直接返回（注意可能为 null/undefined）
  return value ? String(value) : undefined;
};

const usePgSearch = () => {
  const location = useLocation();

  const currentSearch = useMemo(() => {
    const ret = queryString.parse(location.search)
    return ret;
  }, [location.pathname, location.search]);

  //获取 URL 路径中最后一个斜杠/后面的值
  const searchType: BizSearchType = useMemo(() => {
    const pathname = location.pathname;
    const index = pathname.lastIndexOf("/");
    const typeStr = pathname.substring(index + 1);
    if (typeStr === "article") {
      const specialTopicIds = getLastQueryValue(currentSearch, "specialTopicIds");
      if (specialTopicIds === "1") {
        return searchTypeMap["search.guide"];
      } else if (specialTopicIds === "5") {
        return searchTypeMap["search.consensus"];
      }
    }
    return searchTypeMap[`search.${typeStr}`];
  }, [location.pathname, currentSearch])

  return {
    currentSearch,
    searchType,
  };
};

export default usePgSearch;
